<template>
  <div class="login-form-container">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" size="large">
      <div class="logo">
        <img src="@/assets/images/logo.png" width="240px" />
      </div>
      <el-form-item prop="oldPassword">
        <el-input v-model="ruleForm.oldPassword" type="password" placeholder="原密码：" show-password autocomplete="new-password">
          <template #prefix>
            <el-icon class="el-input__icon">
              <lock />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="newPassword">
        <el-input v-model="ruleForm.newPassword" type="password" placeholder="新密码：" show-password autocomplete="new-password">
          <template #prefix>
            <el-icon class="el-input__icon">
              <lock />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="confirmNewPassword">
        <el-input
          v-model="ruleForm.confirmNewPassword"
          type="password"
          placeholder="确认新密码："
          show-password
          autocomplete="new-password"
        >
          <template #prefix>
            <el-icon class="el-input__icon">
              <lock />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
    <div class="login-btn" :style="{ backgroundColor: DEFAULT_PRIMARY }" @click="handleEdit(ruleFormRef)">确 定</div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue"
import { useUserStore } from "@/stores/modules/user"
import { useRouter } from "vue-router"
import { LOGIN_URL } from "@/config"
import { ElNotification } from "element-plus"
import { modifyPasswordApi } from "@/api/modules/login"
import { encryptDes } from "@/utils/des"
import type { ElForm } from "element-plus"
import { DEFAULT_PRIMARY } from "@/config"

const router = useRouter()

interface LoginData {
  oldPassword: string
  newPassword: string
  confirmNewPassword: string
}
type FormInstance = InstanceType<typeof ElForm>
const ruleFormRef = ref<FormInstance>()
const rules = reactive({
  oldPassword: [{ required: true, message: "请输入原密码", trigger: "blur" }],
  newPassword: [{ required: true, message: "请输入新密码", trigger: "blur" }],
  confirmNewPassword: [{ required: true, message: "请确认新密码", trigger: "blur" }]
})
const loading = ref(false)
const ruleForm = reactive<LoginData>({
  oldPassword: "",
  newPassword: "",
  confirmNewPassword: ""
})

// 修改密码
const handleEdit = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async valid => {
    if (!valid) return
    if (ruleForm.newPassword !== ruleForm.confirmNewPassword) {
      ElNotification({
        message: "两次密码不一致",
        type: "error",
        duration: 3000
      })
      return
    }
    loading.value = true
    try {
      const userStore = useUserStore()
      // 1.执行修改密码接口接口
      let formCopy = JSON.parse(JSON.stringify(ruleForm))
      formCopy.oldPassword = encryptDes(formCopy.oldPassword)
      formCopy.newPassword = encryptDes(formCopy.newPassword)
      await modifyPasswordApi(formCopy, userStore.passwordToken)

      // 4.跳转到登录页
      // 清除token
      userStore.setToken("")
      // 清除首次登录修改密码的token
      userStore.setPasswordToken("")
      router.replace(LOGIN_URL)
      ElNotification({
        message: "密码修改成功，请登录！",
        type: "success",
        duration: 3000
      })
    } finally {
      loading.value = false
    }
  })
}

onMounted(() => {
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return
      handleEdit(ruleFormRef.value)
    }
  }
})
</script>

<style scoped lang="scss">
.login-form-container {
  padding: 50px 0;
  .logo {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 40px;
  }
  .el-form {
    .el-form-item {
      :deep(.el-form-item__content) {
        .el-input {
          .el-input__wrapper {
            background-color: #f2f3f5;
            border: 0;
            box-shadow: none;
          }
        }
      }
    }
    .form-item-code {
      :deep(.el-form-item__content) {
        .el-input {
          .el-input-group__append {
            padding: 0 1px 0 10px;
            background-color: inherit;
            box-shadow: none;
          }
        }
      }
    }
  }
  .login-btn {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 42px;
    margin-top: 40px;
    color: #ffffff;
    cursor: pointer;
    border-radius: 10px;
  }
}
</style>
